<template>
  <div>
    <table>
      <thead>
        <tr>
          <th
            v-for="(item, index) in gridColumns"
            :key="index"
            @click="sortFn(item)"
          >
            {{ item.name }}
            <span class="arrow" :class="item.isAsc ? 'asc' : 'dsc'"> </span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in newData" :key="index">
          <td v-for="(v, i) in item" :key="i">{{ v }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  props: ["gridColumns", "gridData", "search"],
  data() {
    return {};
  },
  methods: {
    sortFn(item) {
      // hasOwnProperty() 方法用来判断某个对象是否含有指定的自身属性。
      if (!item.hasOwnProperty("isAsc")) {
        return;
      }
      item.isAsc = !item.isAsc;
      if (typeof this.gridData[0][item.name] == "string") {
        if (item.isAsc) {
          this.gridData.sort((a, b) => {
            // charAt() 方法可返回指定位置的字符。
            if (a[item.name].charAt(0) > b[item.name].charAt(0)) {
              return 1;
            } else if (a[item.name].charAt(0) < b[item.name].charAt(0)) {
              return -1;
            } else {
              return 0;
            }
          });
        } else {
          this.gridData.reverse();
        }
      } else if (typeof this.gridData[0][item.name] == "number") {
        this.gridData.sort((a, b) => {
          return item.isAsc
            ? a[item.name] - b[item.name]
            : b[item.name] - a[item.name];
        });
      }
    },
  },
  mounted() {},
  computed: {
    newData() {
      if (!this.search) {
        return this.gridData;
      } else {
        return this.gridData.filter((v) => {
          // indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置.
          return v.name.toUpperCase().indexOf(this.search.toUpperCase()) != -1;
        });
      }
    },
  },
};
</script>

<style scoped>
</style>